package com.greendizer.api.xmli;

import java.util.List;

import com.greendizer.api.client.AbstractClient;


/**
 * Represents the highest level element in the XMLi.
 */
public class XMLiBuilder extends AbstractElement<Invoice> {

  public static final String XMLi_VERSION = "gd-xmli-1.1";

  /**
   * Adds the given invoice to the current builder.
   * @param invoice The invoice to be added.
   */
  public void addInvoice(Invoice invoice) {
    addChild(invoice);
  }

  /**
   * Removes the given invoice from the current builder.
   * @param invoice The invoice to be removed.
   */
  public void removeInvoice(Invoice invoice) {
    removeChild(invoice);
  }

  /**
   * Returns the invoices contained in the current builder.
   * @return The invoices contained in the current builder.
   */
  public List<Invoice> getInvoices() {
    return getChildren();
  }

  /**
   * Inherited from {@link AbstractElement} but not supported.
   */
  public Double getTotal() {
    throw new UnsupportedOperationException();
  }

  /**
   * Inherited from {@link AbstractElement} but not supported.
   */
  public List<XMLNamespace> getNamespaces() {
    throw new UnsupportedOperationException();
  }

  /**
   * Returns the XMLi representation of builder.
   */
  public String toString() {
    StringBuffer buffer = new StringBuffer();
    buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    buffer.append(String.format("<xmli version=\"%s\" invoice-agent=\"Greendizer Java Library v%s\">", XMLi_VERSION, AbstractClient.VERSION));
    buffer.append("<invoices>");
    for (Invoice invoice : getChildren()) {
      buffer.append("<invoice>");
      buffer.append(invoice.toString());
      buffer.append("</invoice>");
    }
    buffer.append("</invoices>");
    buffer.append("</xmli>");
    return buffer.toString();
  }
}
